<template>
  <!-- 添加任务  -->
  <el-dialog :title="dialogTitle" :visible.sync="visible" width="850px" @close="closeFn">
    <!-- {{ tableData }} -->
    <div class="clear ui-mb10">
      <span class="font-right form-search">
        <el-form ref="formSearch" :inline="true" class="form-search" size="normal">
          <el-form-item label="见证阶段" style="margin-bottom: 0px; margin-right: 10px">
            <el-cascader
              v-model="witnessLinkCode"
              option-max-width="300px"
              class="ui-w120"
              clearable
              :options="initData.taskWitnessLink"
              @change="submitSearchFn"
            />
          </el-form-item>
          <el-input
            v-model.trim="keyWord"
            style="background: #1890ff"
            placeholder="项目名称/编号"
            class="ui-w320"
            @keydown="submitSearchFn"
          >
            <el-button slot="append" type="primary" icon="el-icon-search" @click="submitSearchFn" />
          </el-input>
        </el-form>
      </span>
    </div>
    <el-table
      :key="'table' + type"
      :data="tableData"
      :max-height="300"
      :isdrag="true"
      :no-hover="true"
      stripe
      @select-all="handleSelectAllFn"
      @expand-change="handleExpandChangeFn"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="ui-ml10">
            <!-- :merge-columns="mergeColumns" -->
            <el-table
              :ref="'multipleTable_' + props.$index"
              :key="'multipleTable_' + props.$index"
              :row-key="getRowKeyFn"
              :data="props.row.data.bidSubTaskInfoList"
              border
              :isdrag="true"
              :no-hover="true"
              :header-cell-style="{ background: '#6486C6', color: '#FFFFFF' }"
              :merge-columns="mergeColumns"
              @select="handleSelectFn"
              @select-all="handleSelectAllChildFn(props.row.data.bidSubTaskInfoList)"
              @selection-change="hanldeSelectChangeFn"
            >
              <el-table-column label="选择" align="center" type="selection" width="55" :reserve-selection="true" />
              <el-table-column prop="bidSectionName" label="标段名称" min-width="150" />
              <el-table-column prop="bidSectionCode" label="标段编号" min-width="150" />
              <el-table-column prop="witnessSubTaskName" label="见证阶段" width="80" />
              <el-table-column prop="witnessSubTaskAllocateTime" label="分配时间" width="150">
                <template slot-scope="scope">
                  {{ formatDateFn(scope.row.witnessSubTaskAllocateTime, "yyyy-MM-dd HH:mm") }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="选择" align="center" type="selection" :selectable="() => false" width="55" />
      <el-table-column type="index" :index="indexFn" align="center" label="序号" width="55">
        <template slot-scope="scope">
          {{ (pageObj.currentPage - 1) * pageObj.pageSize + 1 + scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="项目名称" min-width="205">
        <template slot-scope="scope">
          {{ scope.row.data.projectName }}
        </template>
      </el-table-column>
      <el-table-column label="项目编号" width="250" prop="projectCode">
        <template slot-scope="scope">
          {{ scope.row.data.projectCode }}
        </template>
      </el-table-column>
    </el-table>
    <div class="layout-footer ui-pt10">
      <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
        @pagination="subtaskListFn"
      />
    </div>
    <span slot="footer">
      <el-button type="primary" :disabled="!canSubmit" :loading="loading" @click="submitFn">确定</el-button>
      <el-button @click="cancelFn()">取消</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { formatDateFn } from "../../utils/utils";
  import {
    // subtaskList,
    // subtaskAllocateUser,
    subtaskBatchStart,
    subtaskList
  } from "../../api/api.js";
  import { GZAPI_EvaluationTime } from "../../../gz_plugin/api";
  export default {
    name: "AssignDialog",
    components: {},
    props: {
      type: {
        type: String,
        default: ""
      },
      headerTitle: {
        type: String,
        default: ""
      },
      show: {
        type: Boolean,
        default: false
      },
      initData: {
        type: Object,
        default() {
          return {};
        }
      }
    },
    data() {
      return {
        multipleSelection: [],
        updateForm: {
          reason: ""
        },
        dialogTitle: "加入任务",
        userSelected: "",
        taskList: [],
        reasonFlag: false,
        loading: false,
        visible: false,
        keyWord: "",
        witnessLinkCode: "",
        canSubmit: false,
        isSelectAll: false,
        tableData: [],
        tableDataOld: [],
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        mergeColumns: [
          {
            key: "bidSectionName",
            conditions: ["bidSectionName"]
          },
          {
            key: "bidSectionCode",
            conditions: ["bidSectionCode", "bidSectionName"]
          }
        ]
      };
    },
    computed: {
      // visible() {
      //   return this.show;
      // },
      nettyPendData() {
        return this.$websocketNettyPend.getters.pendData;
      }
    },
    watch: {
      // data() {
      //   this.taskList = this.data;
      // },
      nettyPendData: {
        handler(newVal) {
          console.log("addtask netty ws消息变化===============nettyPendData=", newVal);
          if (!newVal || !newVal.data) {
            return;
          }
          console.log("newVal.witnessRecordList", newVal.witnessRecordList);
          // 每次处理1个项目的待定
          Object.keys(newVal.data).forEach((key) => {
            this.tableData.forEach((item, index) => {
              if (item.data.projectCode === newVal.data[key].projectCode) {
                item.data.bidSubTaskInfoList.forEach((itemB, indexB) => {
                  if (itemB.bidSectionCode === newVal.data[key].bidSectionCode) {
                    item.data.bidSubTaskInfoList.splice(indexB, 1);
                  }
                });
                if (!item.data.bidSubTaskInfoList.length) {
                  this.tableData.splice(index, 1);
                }
              }
            });
          });
          // Object.keys(newVal.data).forEach((key) => {
          //   console.log("key", key);
          //   this.topTaskAllData[key].forEach((item) => {
          //     console.log("item", item);
          //     if (item.bidSectionCode === newVal.data[key].bidSectionCode) {
          //       item.witnessSubTaskStatusEnum = "WITNESS_PENDING";
          //       // 当前选中触发this.currProjectData的监听
          //       if (this.currProjectData.bidSectionCode === newVal.data[key].bidSectionCode) {
          //         this.$set(this.currProjectData, "witnessSubTaskStatusEnum", "WITNESS_PENDING");
          //       }
          //     }
          //   });
          // });
          console.log("this.topTaskAllData===s", this.topTaskAllData);
        },
        immediate: true
      },
      show() {
        this.visible = this.show;
        this.multipleSelection = [];
        // this.userSelected = "";
        this.reasonFlag = false;
        if (this.show) {
          this.subtaskListFn();
        }
      },
      tableData: {
        handler() {
          let res = null;
          for (const item of this.tableData) {
            res = item.data.bidSubTaskInfoList.some((child) => child.isSelect);
            if (res) {
              this.canSubmit = res;
              return;
            }
          }
          this.canSubmit = res;
        },
        deep: true
      }
    },
    destroyed() {
      this.tableData = [];
      this.loading = false;
    },
    methods: {
      ...{ formatDateFn },
      indexFn(index) {
        return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
      },
      cancelFn() {
        this.visible = false;
        this.tableData = [];
        this.pageObj.currentPage = 1;
      },
      closeFn() {
        this.keyWord = "";
        this.isSelectAll = false;
        // this.userSelected = "";
        this.multipleSelection = [];
        this.witnessLinkCode = "";
        this.$emit("close");
      },
      submitFn() {
        this.loading = true;
        this.$nextTick(() => {
          this.subtaskBatchStartFn();
        });
      },
      // 搜索
      submitSearchFn() {
        this.multipleSelection = [];
        this.subtaskListFn();
        // this.tableData = this.tableDataOld.filter((item) => {
        //   return (
        //     item.userCode.indexOf(this.keyWord) > -1 ||
        //     item.userName.indexOf(this.keyWord) > -1
        //   );
        // });
      },
      //   /gdw/witness/subtask/list
      async subtaskListFn() {
        // currentPage // 当前页数
        // endTime // 结束时间
        // industry // 枚举值: QT
        // industryType // 枚举值: GCJS,ZFCG,CQJY,TDJY,YPCG
        // pageSize  // 每页条数
        // search // 关键字搜索
        // startTime // 起始时间
        // tenderMode // 枚举值: PUBLIC_BIDDING,INVITE_BIDDING
        // witnessSubTaskStatus // 枚举值: UNASSIGNED,ASSIGNED,WITNESSING,WITNESS_FINISHED,WITNESS_UN_REVIEWED,WITNESS_PASS
        try {
          const p = {
            witnessLinkCode: this.witnessLinkCode[0],
            currentPage: this.pageObj.currentPage, // 当前页数
            pageSize: this.pageObj.pageSize, // 每页条数
            witnessSubTaskStatus: "ASSIGNED", // "ASSIGNED", //this.formSearch.status[0], // 见证状态
            search: this.keyWord // 搜索
          };
          const res = await subtaskList(p);
          if (res.success) {
            if (res.data.data.length === 0 && this.pageObj.currentPage !== 1) {
              this.pageObj.currentPage = 1;
              this.$nextTick(() => {
                this.subtaskListFn();
              });
              return;
            }
            this.isSelectAll = false;
            this.tableData = this.transformDataFn(res.data.result);
            this.pageObj.total = res.data.pageBean.count;
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 批量开启见证任务
      async subtaskBatchStartFn() {
        // this.$emit("submit2", witnessSubTaskIdList.pop());
        // return;
        try {
          console.log("this.multipleSelection", this.multipleSelection);
          // let witnessSubTaskIdList = this.multipleSelection.map((item) => {
          //   return item.data.witnessSubTaskId;
          // });
          const witnessSubTaskIdList = [];
          for (const item of this.tableData) {
            for (const child of item.data.bidSubTaskInfoList) {
              if (child.isSelect) {
                witnessSubTaskIdList.push(child.witnessSubTaskId);
              }
            }
          }
          console.log("witnessSubTaskIdList", witnessSubTaskIdList);
          // return;
          const p = {
            witnessSubTaskIdList
          };
          const res = await GZAPI_EvaluationTime.subtaskBatchStart(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "操作成功",
              single: true
            });
            this.tableData = [];
            this.pageObj.currentPage = 1;
            // this.visible = false; //cancelFn()
            this.$emit("submit2", witnessSubTaskIdList.pop());
            this.$emit("close");
          } else {
            this.$message({
              type: "error",
              message: "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (err) {
          console.error(err);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
        this.loading = false;
      },
      handleSelectAllFn() {
        this.isSelectAll = !this.isSelectAll;
        for (const item of this.tableData) {
          for (const child of item.data.bidSubTaskInfoList) {
            child.isSelect = this.isSelectAll;
            this.$refs[`multipleTable_${item.data.id}`] &&
              this.$refs[`multipleTable_${item.data.id}`].toggleRowSelection(child, child.isSelect);
          }
        }
      },
      handleSelectAllChildFn(selection) {
        // console.log("select all", selection);
        const isSelect = !selection.every((item) => item.isSelect);
        for (const item of selection) {
          item.isSelect = isSelect;
        }
      },
      handleSelectFn(selection, row) {
        row.isSelect = !row.isSelect;
      },
      getRowKeyFn(row) {
        return row.witnessSubTaskId;
      },
      childSelectableFn(row) {
        // console.log("row", row);
        // console.log("index", index);
        return row.isSelect;
      },
      handleExpandChangeFn(row) {
        // console.log("changerow", row);
        // console.log("expandedRows", expandedRows);
        this.$nextTick(() => {
          for (const item of row.data.bidSubTaskInfoList) {
            // console.log(item);
            this.$refs[`multipleTable_${row.data.id}`] &&
              this.$refs[`multipleTable_${row.data.id}`].toggleRowSelection(item, item.isSelect);
          }
        });
      },
      hanldeSelectChangeFn(selection) {
        this.multipleSelection = selection;
      },
      transformDataFn(data) {
        for (const [index, item] of data.entries()) {
          item.data.id = index;
          for (const child of item.data.bidSubTaskInfoList) {
            child.isSelect = false;
          }
        }
        return data;
      }
    }
  };
</script>
<style lang="scss" scoped></style>
